package com.sxjh.controller.ny;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxjh.common.BaseController;
import com.sxjh.common.Constant;
import com.sxjh.common.Result;
import com.sxjh.common.ZPage;
import com.sxjh.config.Authorization;
import com.sxjh.config.ExcelCacheConfig;
import com.sxjh.entity.ExcelEntity;
import com.sxjh.entity.GoodsLocation;
import com.sxjh.entity.Task;
import com.sxjh.entity.WagonNumber;
import com.sxjh.entity.param.ManualConfirmParam;
import com.sxjh.entity.param.UnloadLogDayParam;
import com.sxjh.entity.param.UnloadLogListParam;
import com.sxjh.entity.param.UnloadLogWeighParam;
import com.sxjh.entity.result.*;
import com.sxjh.enums.NodeEnum;
import com.sxjh.enums.TaskStatusEnum;
import com.sxjh.mapper.TaskMapper;
import com.sxjh.mapper.UnloadLogMapper;
import com.sxjh.service.*;
import com.sxjh.uitl.LocalDateTimeUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;


/**
 * <p>
 * 卸货记录  前端控制器
 * </p>
 *
 * @author zixin
 * @since 2021-06-06
 */
@Slf4j
@RestController
@RequestMapping("/api/unload-log")
@Api(tags = "过榜-卸货")
public class UnloadLogController extends BaseController {

    @Autowired
    private IcService icService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private GoodsLocationService goodsLocationService;

    @Autowired
    private UnloadLogService unloadLogService;

    @Autowired
    private IcLogService icLogService;

    @Autowired
    private WagonNumberService wagonNumberService;

    @Autowired
    private FileService fileService;

    @Resource
    private UnloadLogMapper unloadLogMapper;

    @Autowired
    private TaskMapper taskMapper;

    @ApiOperation("过磅")
    @PostMapping("/weigh")
    public Result<UnloadLogWeighResult> weigh(@RequestBody @Validated UnloadLogWeighParam param) {
        if (StringUtils.isNotBlank(param.getWeight())) {
            //吨 转为 kg
            param.setWeight(new BigDecimal(param.getWeight()).multiply(new BigDecimal("1000")).toString());
        }
        long st = System.currentTimeMillis();
        log.info("===过磅开始参数taskId:{},,,weight:{},,,icNumber:{},,,vehNumber:{}", param.getTaskId(), param.getWeight(), param.getIcNumber(), param.getVehNumber());
        //IC卡校验
        IcWagonNumberResult icWagonNumber = icService.queryByIcNumber(param.getIcNumber());
        if (icWagonNumber == null) return err("IC卡卡号在系统中不存在");
        if (icWagonNumber.getWagonNumberId() == null || icWagonNumber.getWagonNumberId() == 0 || StrUtil.isBlank(icWagonNumber.getNumber2()))
            return err("IC卡未绑定车辆信息");
        Integer wagonNumberId = icWagonNumber.getWagonNumberId();

        //同一辆车的2次过磅间隔必须大于10分钟，防止重复提交
        //查询此车的最新过磅时间(包括初磅时间和复磅时间)
        LambdaQueryWrapper<Task> taskCheckQuery = new LambdaQueryWrapper<Task>().eq(Task::getWagonNumberId, wagonNumberId)
                .in(Task::getStatus, com.google.common.collect.Lists.newArrayList(2, 3));
        taskCheckQuery.orderByDesc(Task::getTareAt);
        taskCheckQuery.last(" limit 30");
        List<Task> taskCheckList = taskService.list(taskCheckQuery);
        if (CollUtil.isNotEmpty(taskCheckList)) {
            LocalDateTime maxAt = taskCheckList.get(0).getTareAt();
            Optional<Task> maxGrossAtTaskOptional = taskCheckList.stream().filter(ta -> ta.getGrossAt() != null).max(Comparator.comparing(Task::getGrossAt));
            if (maxGrossAtTaskOptional.isPresent()) {
                LocalDateTime maxGrossAt = maxGrossAtTaskOptional.get().getGrossAt();
                maxAt = maxAt.isAfter(maxGrossAt) ? maxAt : maxGrossAt;
            }
            long diff = cn.hutool.core.date.LocalDateTimeUtil.between(maxAt, LocalDateTime.now(), ChronoUnit.SECONDS);
            //默认10分钟
            long weightIntervalTime = 9;
            TransSettingResult transSetting = taskMapper.getTransSetting();
            if (transSetting != null && transSetting.getInternalReshipmentInterval() != null) {
                weightIntervalTime = transSetting.getInternalReshipmentInterval();
            }
            if (diff <= weightIntervalTime * 60)  return err("距上次过磅时间间隔不能小于" + weightIntervalTime + "分钟");
        }

        //车辆配置中皮重
        double tare = Convert.toDouble(icWagonNumber.getTare());
        //毛重
        double capacity = Convert.toDouble(icWagonNumber.getCapacity());
        long end1 = System.currentTimeMillis();
        log.info("===过磅查询IC信息taskId:{},,,icNumber:{},,,耗时:{}", param.getTaskId(), param.getIcNumber(), (end1 - st));
        // 判断空磅还是重磅
        if (StrUtil.isNotBlank(param.getTaskId())) {
            if (Convert.toDouble(param.getWeight()) <= (Convert.toDouble(icWagonNumber.getTareFloatingValue()) - Convert.toDouble(tare)))
                return err("空磅重量异常，低于皮重下限" + (Convert.toDouble(icWagonNumber.getTareFloatingValue()) - Convert.toDouble(tare)) + "KG");
            LambdaQueryWrapper<Task> taskQuery = new LambdaQueryWrapper<Task>().eq(Task::getWagonNumberId, wagonNumberId).eq(Task::getStatus, TaskStatusEnum.TWO.getValue());
            List<Task> taskList = taskService.list(taskQuery);
            if (CollUtil.isNotEmpty(taskList)) {
                return err("该司机存在进行中的任务,无法过空磅");
            }
            Task task = taskService.getById(param.getTaskId());
            if (TaskStatusEnum.ONE.getValue() != task.getStatus()) {
                return err("该派车单状态已经是执行中或完成，不可再过空磅");
            }
            LambdaQueryWrapper<Task> taskDoneQuery = new LambdaQueryWrapper<Task>().eq(Task::getWagonNumberId, wagonNumberId)
                    .eq(Task::getStatus, TaskStatusEnum.THREE.getValue());
            taskDoneQuery.orderByDesc(Task::getGrossAt);
            taskCheckQuery.last(" limit 1");
            List<Task> taskDoneList = taskService.list(taskDoneQuery);
            if (CollUtil.isNotEmpty(taskDoneList)) {
                Task taskDone = taskDoneList.get(0);
                if (taskDone != null && !param.getTaskId().equals(taskDone.getId().toString())) {
                    BigDecimal diffWeight = (new BigDecimal(taskDone.getGross()).multiply(new BigDecimal(1000)))
                            .subtract(new BigDecimal(param.getWeight()));
                    if (Math.abs(diffWeight.doubleValue()) <= 10) {
                        return err("重复过磅!");
                    }
                }
            }
            // 空磅称重保存
            task.setTare(param.getWeight());
            task.setTareAt(LocalDateTime.now());
            task.setCurrNode(NodeEnum.ONE.getOrder());
            task.setStatus(TaskStatusEnum.TWO.getValue());
            task.setUpdatedAt(LocalDateTimeUtil.getTime());
            boolean isU = taskService.updateById(task);
            if (isU) {
                try {
                    taskService.savePhpFile(task.getId(), param.getFile1(), param.getFile2(), true);
                } catch (Exception e) {
                    log.error("保存图片异常111：{}", e.getMessage());
                }
                long end2 = System.currentTimeMillis();
                log.info("===过磅保存图片taskId:{},,,icNumber:{},,,耗时:{}", param.getTaskId(), param.getIcNumber(), (end2 - st));
            }
            String number = unloadLogService.serial();
            unloadLogService.saveUnloadLog(param, task, icWagonNumber, number);

            // 空磅称重日志保存
            icLogService.saveLog(wagonNumberId, param.getIcNumber(), param.getWeight(), param.getImg1(), param.getImg2(), Constant.UNLOAD_EMPTY);
            long end3 = System.currentTimeMillis();
            log.info("===过磅保存日志taskId:{},,,icNumber:{},,,耗时:{}", param.getTaskId(), param.getIcNumber(), (end3 - st));

            // 返回显示信息
            if (isU) {
                UnloadLogWeighResult result = convertUnloadLogWeighResult(param, icWagonNumber, number, true);
                long end4 = System.currentTimeMillis();
                log.info("===过磅返回信息taskId:{},,,icNumber:{},,,耗时:{}", param.getTaskId(), param.getIcNumber(), (end4 - st));
                return cus(0, "提交空磅数据成功", result);
            }
            return err("保存空磅数据出错");
        } else {
            if (tare >= Convert.toDouble(param.getWeight())) return err("异常：毛重小于皮重");
            if ((Convert.toDouble(param.getWeight()) - Convert.toDouble(capacity)) >= Convert.toDouble(icWagonNumber.getGrossFloatingValue()))
                return err("重磅重量异常，高于载重最大值" + (Convert.toDouble(capacity) + Convert.toDouble(icWagonNumber.getGrossFloatingValue())) + "KG");
            //车辆信息配置的净重
            double theoryNet = capacity - tare;
            //实际的净重
            LambdaQueryWrapper<Task> taskQuery = new LambdaQueryWrapper<Task>().eq(Task::getWagonNumberId, wagonNumberId).eq(Task::getStatus, TaskStatusEnum.TWO.getValue());
            List<Task> taskList = taskService.list(taskQuery);
            if (CollUtil.isEmpty(taskList)) {
                return err("请先进行空磅称重");
            }
            if (taskList.size() > 1) {
                return err("只能有一个派车单在进行中");
            }
            Task task = taskList.get(0);
            double realNet = Convert.toDouble(param.getWeight()) - Convert.toDouble(task.getTare());
            if (realNet <= 0) {
                return err("异常：毛重小于皮重!");
            }
            if ((Convert.toDouble(realNet) - Convert.toDouble(theoryNet)) >= Convert.toDouble(icWagonNumber.getFloatingValue()))
                return err("净重值不能大于净重最大值" + (Convert.toDouble(theoryNet) + Convert.toDouble(icWagonNumber.getFloatingValue())) + "KG");
            //重复提交
            //long diff = cn.hutool.core.date.LocalDateTimeUtil.between(task.getTareAt(), LocalDateTime.now(), ChronoUnit.MINUTES);
            //TODO 暂时屏蔽
            //if (diff < INTERVAL) return err("距空磅时间小于5分钟");
            //过重磅
            //校验装车点是否是否必须拍照确认，是否跳过，否者提示
            GoodsLocation goodsLocation = goodsLocationService.getById(task.getLoadId());
            long end2 = System.currentTimeMillis();
            log.info("===过磅装车点信息taskId:{},,,icNumber:{},,,耗时:{}", param.getTaskId(), param.getIcNumber(), (end2 - st));
            if (goodsLocation == null) return err("装车点不存在");
            boolean flag = checkIsSkip(task, goodsLocation);
            if (flag) return err("装车点没有拍照确认");
            // 查看最新的卸货记录
            param.setTaskId(task.getId() + "");
            long end3 = System.currentTimeMillis();
            //log.info("===过磅卸货记录taskId:{},,,icNumber:{},,,耗时:{}", param.getTaskId(), param.getIcNumber(), (end3 - st));
            task.setGross(param.getWeight());
            task.setGrossAt(LocalDateTime.now());
            task.setCurrNode(NodeEnum.THREE.getOrder());
            //判断卸车点是否需要拍照和确认
            GoodsLocation goodsDownLocation = goodsLocationService.getById(task.getUnloadId());
            if (goodsDownLocation.getPhotoFlag() == -1 || goodsDownLocation.getConfirmFlag() == -1) {
                if (task.getCurrNode() >= NodeEnum.THREE.getOrder()) {
                    return err("当前这个派车单还没走完流程");
                }
                //过完复磅还有节点
                task.setStatus(TaskStatusEnum.TWO.getValue());
            } else {
                task.setStatus(TaskStatusEnum.THREE.getValue());
            }
            task.setUpdatedAt(LocalDateTimeUtil.getTime());
            boolean isU = taskService.updateById(task);
            if (isU) {
                try {
                    taskService.savePhpFile(task.getId(), param.getFile1(), param.getFile2(), false);
                } catch (Exception e) {
                    log.error("保存图片异常2222：{}", e.getMessage());
                }
                long end4 = System.currentTimeMillis();
                log.info("===过磅保存图片taskId:{},,,icNumber:{},,,耗时:{}", param.getTaskId(), param.getIcNumber(), (end4 - st));
            }

            String number = unloadLogService.getSerives(icWagonNumber.getWagonNumberId());
            unloadLogService.saveUnloadLog(param, task, icWagonNumber, number);

            //保存日志
            icLogService.saveLog(wagonNumberId, param.getIcNumber(), param.getWeight(), param.getImg1(), param.getImg2(), Constant.UNLOAD_WEIGHT);

            // 返回显示信息
            if (isU) {
                param.setTaskId(task.getId() + "");
                UnloadLogWeighResult result = convertUnloadLogWeighResult(param, icWagonNumber, number, false);
                long end5 = System.currentTimeMillis();
                log.info("===过磅返回taskId:{},,,icNumber:{},,,耗时:{}", param.getTaskId(), param.getIcNumber(), (end5 - st));
                return cus(0, "提交重磅数据成功", result);
            }
            return err("保存重磅数据出错");
        }
    }

    @ApiOperation("过磅2(需要同时上传图片)")
    @PostMapping(value = "/weigh2", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @ApiImplicitParams({@ApiImplicitParam(name = "files", value = "文件上传", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "weight", value = "磅数", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "icNumber", value = "ic卡编号", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "vehNumber", value = "车牌号", required = false, dataTypeClass = String.class)})
    public Result<UnloadLogWeighResult> weigh2(@ApiParam(hidden = true) MultipartFile[] files, String weight, String icNumber, String vehNumber) {
        if (StrUtil.isBlank(weight)) return err("磅数不能为空");
        if (!(NumberUtil.isDouble(weight) || NumberUtil.isNumber(weight))) return err("磅数必须是数字");
        if (StrUtil.isEmpty(icNumber)) return err("卡号不能为空");
        if (files == null || files.length != 2) return err("请上传两张图片");
        UnloadLogWeighParam entity = new UnloadLogWeighParam();
        entity.setIcNumber(icNumber);
        entity.setWeight(weight);
        entity.setFile1(files[0]);
        entity.setFile2(files[1]);
        entity.setVehNumber(vehNumber);
        //entity.setImg1(img1);
        //entity.setImg2(img2);
        return weigh(entity);
    }

    @ApiOperation("过磅3(需要同时上传图片)")
    @PostMapping(value = "/weigh3", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @ApiImplicitParams({@ApiImplicitParam(name = "file1", value = "文件上传", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "file2", value = "文件上传", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "weight", value = "磅数", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "icNumber", value = "ic卡编号", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "taskId", value = "任务id", dataTypeClass = String.class),
            @ApiImplicitParam(name = "vehNumber", value = "车牌号", required = false, dataTypeClass = String.class)})
    public Result<UnloadLogWeighResult> weigh3(@ApiParam(hidden = true) MultipartFile file1, @ApiParam(hidden = true) MultipartFile file2,
                                               String weight, String icNumber, String taskId, String vehNumber) {
        if (StrUtil.isBlank(weight)) return err("磅数不能为空");
        if (!(NumberUtil.isDouble(weight) || NumberUtil.isNumber(weight))) return err("磅数必须是数字");
        if (StrUtil.isBlank(icNumber)) return err("卡号不能为空");
        if (file1 == null || file2 == null) {
            return err("请上传过磅图片");
        }
        if (StrUtil.isNotBlank(taskId) && "null".equals(taskId)) {
            taskId = "";
        }
        UnloadLogWeighParam entity = new UnloadLogWeighParam();
        entity.setIcNumber(icNumber);
        entity.setWeight(weight);
        entity.setFile1(file1);
        entity.setFile2(file2);
        //entity.setImg1(img1);
        //entity.setImg2(img2);
        entity.setTaskId(taskId);
        entity.setVehNumber(vehNumber);
        return weigh(entity);
    }

    @ApiOperation("初磅派车单列表查询")
    @PostMapping(value = "/taskList")
    @ApiImplicitParams({@ApiImplicitParam(name = "icNumber", value = "ic卡编号", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "vehNumber", value = "车牌号", required = false, dataTypeClass = String.class)})
    Result<List<PlanedTaskListResult>> taskList(String icNumber, String vehNumber) {
        log.info("===初磅派车单列表查询icNumber:{},,,vehNumber:{}", icNumber, vehNumber);
        if (StrUtil.isBlank(icNumber)) return err("卡号不能为空");
        if (StrUtil.isBlank(vehNumber)) {
            return err("未识别到车牌号");
        }
        IcWagonNumberResult icWagonNumber = icService.queryByIcNumber(icNumber);
        if (icWagonNumber == null) return err("IC卡卡号在系统中不存在");
        if (icWagonNumber.getWagonNumberId() == null || icWagonNumber.getWagonNumberId() == 0 || StrUtil.isBlank(icWagonNumber.getNumber2()))
            return err("IC卡未绑定车辆信息");
        if (!vehNumber.equals(icWagonNumber.getNumber2())) {
            return err("过磅车牌号和IC卡绑定的车牌号不一致");
        }
        //如果有执行中的派车单，优先返回
        List<PlanedTaskListResult> taskList = taskService.taskList(icNumber, TaskStatusEnum.TWO.getValue());
        if (CollUtil.isNotEmpty(taskList)) {
            return cus(1, "初磅任务列表查询", taskList);
        }
        return cus(0, "初磅任务列表查询", taskService.taskList(icNumber, TaskStatusEnum.ONE.getValue()));
    }

    @ApiOperation("内部倒运物料日报")
    @GetMapping("/day")
    @Authorization("unload-log.day")
    Result<List<UnloadLogDayResult>> day(@Validated UnloadLogDayParam param) {
        return ok(unloadLogService.day(param));
    }

    @ApiOperation("内部倒运明细报表")
    @GetMapping("/details")
    @Authorization("unload-log.list")
    Result<List<UnloadLogListResult>> details(@Validated UnloadLogListParam param) {
        return ok(unloadLogService.details(param));
    }

    @ApiOperation("内部倒运查询")
    @GetMapping
    @Authorization("unload-log.list")
    Result<List<UnloadLogListResult>> list(@Validated UnloadLogListParam param) {
        return ok(unloadLogService.list(param));
    }

    @ApiOperation("内部倒运查询分页")
    @GetMapping("/page")
    @Authorization("unload-log.list")
    Result<ZPage<UnloadLogListResult>> page(@Validated UnloadLogListParam param) {
        ZPage<UnloadLogListResult> page = unloadLogService.page(param);
        List<UnloadLogListResult> records = page.getRecords();
        records.forEach(result -> {
            String netWeight = result.getNetWeight();
            if (StrUtil.isNotBlank(netWeight)) {
                double d = Double.parseDouble(netWeight);
                String weight = d > 0 ? netWeight : null;
                result.setNetWeight(weight);
            }
        });
        return ok(page);
    }

    @ApiOperation("内部倒运Excel导出")
    @GetMapping("/excel")
    @Authorization("unload-log.list")
    Result<String> excel(@Validated UnloadLogListParam param) {
        String id = ExcelCacheConfig.setParam(param, ExcelEntity.Type.UNLOAD);
        return ok(id);
    }

    @ApiOperation("打印地榜单")
    @GetMapping("/print/{orderNo}")
    public Result<UnloadLogWeighResult> print(@PathVariable("orderNo") String orderNo) {
        if (StrUtil.isBlank(orderNo)) return err("派车单号不能为空");
        LambdaQueryWrapper<Task> query = new LambdaQueryWrapper<>();
        query.eq(Task::getOrderNo, orderNo);
        Task task = taskService.getOne(query);
        if (task == null) {
            return err("派车单号不存在");
        }
        UnloadLogWeighParam param = new UnloadLogWeighParam();
        param.setTaskId(task.getId() + "");
        param.setWeight(task.getGross());
        boolean flag = false;
        if (task.getGrossAt() == null) {
            flag = true;
            param.setWeight(task.getTare());
        }
        WagonNumber wagonNumber = wagonNumberService.getById(task.getWagonNumberId());
        IcWagonNumberResult icWagonNumber = new IcWagonNumberResult();
        //icWagonNumber.setPrinting();
        icWagonNumber.setNumber(wagonNumber.getNumber());
        icWagonNumber.setNumber2(wagonNumber.getNumber());
        String number = unloadLogService.getSerives(task.getWagonNumberId());
        UnloadLogWeighResult info = convertUnloadLogWeighResult(param, icWagonNumber, number, flag);
        return ok(info);
    }

    @ApiOperation("装/卸货点人工确认")
    @PostMapping("/manual-confirm")
    public Result<Object> manualConfirm(@RequestBody ManualConfirmParam param) {

        String orderNo = param.getOrderNo();
        LambdaQueryWrapper<Task> taskQuery = new LambdaQueryWrapper<Task>().eq(Task::getOrderNo, orderNo).eq(Task::getStatus, TaskStatusEnum.TWO.getValue());
        List<Task> taskList = taskService.list(taskQuery);
        if (CollUtil.isEmpty(taskList)) {
            return err("没有进行中的任务");
        }

        Task task = taskList.get(0);
        String img1 = param.getImg1();
        String img2 = param.getImg2();
        Integer type = param.getType();
        if (type == 1) {
            //装货点拍照
            task.setUpImg(img1);
            task.setUpImgTwo(img2);
            task.setCurrNode(NodeEnum.TWO.getOrder());
            task.setStatus(TaskStatusEnum.TWO.getValue());
        } else if (type == 2) {
            //卸货点拍照
            task.setDownImg(img1);
            task.setDownImgTwo(img2);
            task.setCurrNode(NodeEnum.FOUR.getOrder());
            //判断卸车点是否需要拍照和确认
            GoodsLocation goodsDownLocation = goodsLocationService.getById(task.getUnloadId());
            if (goodsDownLocation.getConfirmFlag() == 1) {
                task.setStatus(TaskStatusEnum.TWO.getValue());
            } else {
                task.setStatus(TaskStatusEnum.THREE.getValue());
            }
        } else {
            //卸货点确认
            task.setCurrNode(NodeEnum.FIVE.getOrder());
            task.setStatus(TaskStatusEnum.THREE.getValue());
        }
        task.setUpdatedAt(LocalDateTimeUtil.getTime());
        taskService.updateById(task);
        return Result.cus(200, "提交成功", task);
    }

    private boolean checkIsSkip(Task task, GoodsLocation goodsLocation) {
        if (goodsLocation.getPhotoFlag() != null && goodsLocation.getPhotoFlag() == -1) {
            //装车点需要拍照，没有跳过,装车点照片为空
            return task.getUpIsSkip() == 2 && StrUtil.isBlank(task.getUpImg()) && StrUtil.isBlank(task.getUpImgTwo());
        }
        return false;
    }

    private UnloadLogWeighResult convertUnloadLogWeighResult(UnloadLogWeighParam param, IcWagonNumberResult icWagonNumber, String number, boolean isFirst) {
        TaskListResult param1 = new TaskListResult();
        param1.setId(Integer.valueOf(param.getTaskId()));
        IPage<TaskListResult> iPage = taskService.list(new Page(1, 10), param1);
        if (iPage != null && CollUtil.isNotEmpty(iPage.getRecords())) {
            TaskListResult taskDetail = iPage.getRecords().get(0);
            UnloadLogWeighResult unloadLogWeighResult = new UnloadLogWeighResult();
            BeanUtil.copyProperties(taskDetail, unloadLogWeighResult);
            unloadLogWeighResult.setLoadName(taskDetail.getLocationUpName());
            unloadLogWeighResult.setUnloadName(taskDetail.getLocationDownName());
            unloadLogWeighResult.setPrinting(taskDetail.getPrinting());
            unloadLogWeighResult.setVehNumber(icWagonNumber.getNumber2());
            List<UnloadLogWeighResult.WeighInfo> weighInfoList = Lists.newArrayList();
            if (isFirst) {
                UnloadLogWeighResult.WeighInfo weighInfo = new UnloadLogWeighResult.WeighInfo();
                weighInfo.setType(NodeEnum.ONE.getOrder());
                weighInfo.setTypeName(NodeEnum.ONE.getDescription());
                weighInfo.setWeighingTime(taskDetail.getTareAt());
                weighInfo.setNumber(number);
                //weighInfo.setRough(taskDetail.);
                if (StrUtil.isNotBlank(param.getWeight())) {
                    weighInfo.setTare(Double.parseDouble(param.getWeight()) + "");
                }
                //weighInfo.setNetWeight();
                weighInfoList.add(weighInfo);
            } else {
                UnloadLogWeighResult.WeighInfo weighInfo1 = new UnloadLogWeighResult.WeighInfo();
                weighInfo1.setType(NodeEnum.ONE.getOrder());
                weighInfo1.setTypeName(NodeEnum.ONE.getDescription());
                weighInfo1.setWeighingTime(taskDetail.getTareAt());
                //weighInfo1.setRough(taskDetail.);
                if (StrUtil.isNotBlank(taskDetail.getTare())) {
                    //吨->KG
                    weighInfo1.setTare((new BigDecimal(taskDetail.getTare())).multiply(BigDecimal.valueOf(1000)).toString());
                }
                //weighInfo1.setNetWeight();
                UnloadLogWeighResult.WeighInfo weighInfo2 = new UnloadLogWeighResult.WeighInfo();
                weighInfo2.setType(NodeEnum.THREE.getOrder());
                weighInfo2.setTypeName(NodeEnum.THREE.getDescription());
                weighInfo2.setWeighingTime(taskDetail.getGrossAt());
                double rough = new Double("0");
                if (StrUtil.isNotBlank(param.getWeight())) {
                    rough = Double.parseDouble(param.getWeight());
                    weighInfo2.setRough(rough + "");
                }
                double tare = new Double("0");
                if (StrUtil.isNotBlank(taskDetail.getTare())) {
                    tare = new BigDecimal(taskDetail.getTare()).multiply(BigDecimal.valueOf(1000)).doubleValue();
                    weighInfo2.setTare(tare + "");
                }
                weighInfo2.setNumber(number);

                double netWeight = rough - tare;
                if (netWeight > 0) {
                    weighInfo2.setNetWeight(netWeight + "");
                }
                weighInfoList.add(weighInfo1);
                weighInfoList.add(weighInfo2);
            }
            unloadLogWeighResult.setWeighInfoList(weighInfoList);
            return unloadLogWeighResult;
        }
        return null;
    }

}